import tkinter as tk
from tkinter import ttk, messagebox
import requests
import json


class ClientGui:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("URL Probing Client")

        # Define variables
        self.service_url = tk.StringVar()
        self.method = tk.StringVar()
        self.payload_text = None
        self.service_url.set("http://127.0.0.1:8888/prober")
        self.method.set("Get")

        self.set_function()

    def set_function(self):
        """Some GUI function of UPC"""
        self.set_service_url()
        self.set_method()
        self.set_payload()
        self.set_button()

        self.root.resizable(0, 0)
        self.root.attributes("-toolwindow", 2)
        self.root.bind("<Return>", self.send_request)
        self.root.wm_attributes('-topmost', 1)

    def set_service_url(self):
        service_url_label = tk.Label(self.root, text="Service url")
        service_url_entry = tk.Entry(self.root, textvariable=self.service_url, width=50)
        service_url_label.grid(row=0, column=0, ipadx=5, ipady=5, padx=5, pady=5)
        service_url_entry.grid(row=0, column=1, ipadx=5, ipady=5, padx=5, pady=5)

    def set_method(self):
        method_label = tk.Label(self.root, text="Request method")
        method_combobox = ttk.Combobox(self.root, textvariable=self.method,
                                       values=["Get", "Post"], state="readonly")
        method_label.grid(row=1, column=0, ipadx=5, ipady=5, padx=5, pady=5)
        method_combobox.grid(row=1, column=1, ipadx=5, ipady=5, padx=5, pady=5)

    def set_button(self):
        """To send request and clear text box"""
        send_button = tk.Button(self.root, text="Send", command=self.send_request)
        send_button.grid(row=3, column=0, ipadx=5, ipady=5, padx=5, pady=5, columnspan=2)

        clear_button = tk.Button(self.root, text="Clear", command=self.clear)
        clear_button.grid(row=3, column=1, ipadx=5, ipady=5, padx=5, pady=5, columnspan=2)

    def set_payload(self):
        """Text box to write payload information"""
        self.payload_text = tk.Text(self.root, width=50, height=20)
        self.payload_text.grid(row=2, column=0, ipadx=5, ipady=5, padx=5, pady=5, columnspan=2)

    def clear(self):
        self.payload_text.delete("1.0", tk.END)

    def write_to_text(self, message):
        """Write text to tex box"""
        self.clear()
        self.payload_text.insert("end", message)
        self.payload_text.see("end")

    def send_request(self, event=None):
        if not self.check():
            return False
        _dict = {
            "Get": self.get_request,
            "Post": self.post_request
        }
        _dict[self.method.get()]()

    def check(self):
        if self.service_url.get() == "":
            self.write_to_text("The server address has not been entered")
            return False
        if self.method.get() == "":
            self.write_to_text("No request method has been selected")
            return False
        return True

    def get_request(self):
        url = self.service_url.get()
        _res = requests.get(url)
        _dict = json.loads(_res.text)
        _res = json.dumps(_dict, sort_keys=True, indent=2, ensure_ascii=False)
        messagebox.showinfo("response", _res)

    def post_request(self):
        url = self.service_url.get()
        _json = self.payload_text.get("1.0", "end")
        if _json.replace("\n", "") == "":
            self.write_to_text("The payload of post request has not been entered")
            return False
        headers = {
            "Content-Type": "application/json; charset=UTF-8"
        }
        _res = requests.post(url, data=_json, headers=headers)
        _dict = json.loads(_res.text)
        _res = json.dumps(_dict, sort_keys=True, indent=2, ensure_ascii=False)
        messagebox.showinfo("response", _res)

    def run(self):
        """To run GUI"""
        self.root.mainloop()


if __name__ == '__main__':
    ClientGui().run()
